/*
 * Flashlib - QB9 common Flash library
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.qb9.flashlib.input
{
	import com.qb9.flashlib.interfaces.IDisposable;
	
	import flash.display.Stage;
	import flash.events.KeyboardEvent;
	import flash.utils.Proxy;
	import flash.utils.flash_proxy;

	/**
	 * Keeps track of the keyboard keys pressed at a certain moment.
	 * To check the state of a certain key, you check the corresponding
	 * attribute of this object. The keys supported "aliases" are those
	 * specified on the docs of the Shortcut class
	 * 
	 * @see com.qb9.flashlib.input.Shortcut#toKeyCode()
	 */

	public dynamic class Keys extends Proxy implements IDisposable
	{
		protected var stage:Stage;
		protected var keys:Object;
		
		public function Keys(stage:Stage)
		{
			this.stage = stage;
		}
		
		public function start() : void
		{
			keys = {};
			stage.addEventListener(KeyboardEvent.KEY_DOWN, add);
			stage.addEventListener(KeyboardEvent.KEY_UP, remove);
		}
		
		public function stop() : void
		{
			keys = {};
			stage.removeEventListener(KeyboardEvent.KEY_DOWN, add);
			stage.removeEventListener(KeyboardEvent.KEY_UP, remove);
		}
		
		protected function add(e:KeyboardEvent) : void
		{
			keys[ e.keyCode ] = true;
			keys[ e.charCode ] = true;
		}
		
		protected function remove(e:KeyboardEvent) : void
		{
			keys[ e.keyCode ] = false;
			keys[ e.charCode ] = false;
		}
		
		public function isDown(key:String):Boolean
		{
			var code:int = Shortcut.toKeyCode(key);
			return code !== -1 && !!keys[code];
		}
		
		override flash_proxy function getProperty(name:*):*
		{
			return isDown(String(name));
		}
		
		public function dispose():void
		{
			stop();
			stage = null;
		}
		
	}
}